package com.guli.order.config;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.guli.order.vo.PayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Author zzb
 * @Date 2024/4/22 16:42
 * @Version 1.0
 */
@Component
@Slf4j
public class AliPayTemplate {
    //app_id
    @Value("${alipay.appId}")
    private String appId;
    //your private_key
    @Value("${alipay.privateKey}")
    private String privateKey;
    //alipay_public_key
    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;
    //setNotifyUrl
    @Value("${alipay.notifyUrl}")
    private String notifyUrl;
    //setReturnUrl
    @Value("${alipay.returnUrl}")
    private String returnUrl;

    public String pay(PayVo payVo) {
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
                appId,
                privateKey,
                "json",
                "UTF-8",
                alipayPublicKey,
                "RSA2"
        );
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(notifyUrl);
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(returnUrl);
        //
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", payVo.getOut_trade_no());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", payVo.getTotal_amount());
        //订单标题，不可使用特殊符号
        bizContent.put("subject", payVo.getSubject());
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        bizContent.put("timeout_express", "1m");
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request, "POST");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        String pageRedirectionData = Objects.requireNonNull(response).getBody();
        if (response.isSuccess()) {
            log.info("{}  => 调用成功", payVo.getOut_trade_no());
        } else {
            log.info("{}  => 调用失败", payVo.getOut_trade_no());
        }
        return pageRedirectionData;
    }
}
